#!/bin/bash

# Quick dependency installer for Java Decompiler MCP Server

echo "🔧 Installing Java Decompiler MCP Server Dependencies..."

# Create tools directory
mkdir -p ./tools

# Download CFR if not exists
if [[ ! -f "./tools/cfr.jar" ]]; then
    echo "📥 Downloading CFR decompiler..."
    if command -v curl >/dev/null 2>&1; then
        curl -L -o ./tools/cfr.jar "https://github.com/leibnitz27/cfr/releases/download/0.152/cfr-0.152.jar"
    elif command -v wget >/dev/null 2>&1; then
        wget -O ./tools/cfr.jar "https://github.com/leibnitz27/cfr/releases/download/0.152/cfr-0.152.jar"
    else
        echo "❌ Neither curl nor wget found. Please install one of them."
        exit 1
    fi
    echo "✅ CFR downloaded"
else
    echo "✅ CFR already exists"
fi

# Check Java
if command -v java >/dev/null 2>&1; then
    echo "✅ Java found: $(java -version 2>&1 | head -n1)"
else
    echo "⚠️  Java not found. Installing OpenJDK 11..."
    
    # Try to install Java based on the system
    if command -v apt-get >/dev/null 2>&1; then
        sudo apt-get update && sudo apt-get install -y openjdk-11-jdk
    elif command -v yum >/dev/null 2>&1; then
        sudo yum install -y java-11-openjdk java-11-openjdk-devel
    elif command -v brew >/dev/null 2>&1; then
        brew install openjdk@11
    else
        echo "❌ Cannot install Java automatically. Please install Java 8+ manually."
        echo "   Ubuntu/Debian: sudo apt-get install openjdk-11-jdk"
        echo "   CentOS/RHEL: sudo yum install java-11-openjdk"
        echo "   macOS: brew install openjdk@11"
        exit 1
    fi
fi

# Set environment variables
echo "🔧 Setting up environment..."
CFR_PATH=$(realpath ./tools/cfr.jar)

# Create or update .env file
cat > .env << EOF
# Java Decompiler MCP Server Configuration
CFR_PATH="$CFR_PATH"
EOF

echo "✅ Setup complete!"
echo "🚀 You can now run: npm start"